What are the differences between 'new' and 'malloc()' for memory allocation in C++?
What are the differences between "new" and "malloc()" for memory allocation in C++?
18304-Aug-2023
Updated on 06-Aug-2023
Home / DeveloperSection / Forums / What are the differences between "new" and "malloc()" for memory allocation in C++?
Aryan Kumar
06-Aug-2023The
new
andmalloc()
operators are both used to allocate memory dynamically in C++. However, there are some key differences between the two operators.new
is an operator, whilemalloc()
is a function. This means thatnew
can be used with expressions, whilemalloc()
cannot. For example, we can writeint* p = new int[10]
, but we cannot writeint* p = malloc(sizeof(int) * 10)
.new
calls the constructor of the type being allocated, whilemalloc()
does not. This means that if we allocate an object of a class type usingnew
, the class's constructor will be called automatically. If we allocate an object of a primitive type usingnew
, the default constructor will be called automatically.new
throws an exception if it fails to allocate memory, whilemalloc()
returns a null pointer. This means that if we usenew
to allocate memory and the allocation fails, our program will crash. If we usemalloc()
to allocate memory and the allocation fails, our program will continue to run, but the pointer we get back will be null.In general, it is recommended to use
new
instead ofmalloc()
for memory allocation in C++.new
is more convenient to use, and it is safer because it will not crash your program if it fails to allocate memory. However, there are some cases where you may need to usemalloc()
instead ofnew
. For example, if you are working with a legacy C code that usesmalloc()
, you may need to usemalloc()
in your C++ code to maintain compatibility.Here is a table summarizing the differences between
new
andmalloc()
:new
malloc()